<template>
  <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">

    <!-- 主要内容 -->
    <el-main>
      <el-header>
        <el-col :span="6">
          <span>项目编号：{{ formData.projectCode }}</span>
        </el-col>
        <el-col :span="6">
          <span>项目名称：{{ formData.projectName  }}</span>
        </el-col>
        <el-col :span="6">
          <span>采购类别：{{ formData.categoryName }}</span>
        </el-col>
        <el-col :span="6">
          <span>采购类别：{{ formData.budget }}元</span>
        </el-col>
      </el-header>

      <!-- 归档文件 table -->
      <br><br><span>归档文件：</span>
      <el-table :data="projectTable" style="width: 100%" class="table" border v-loading="loading">
        <el-table-column prop="fileCategory" label="文件类别"></el-table-column>
        <el-table-column prop="fileName" label="文件名"></el-table-column>
        <el-table-column prop="fileArchiveTime" label="归档时间"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button style="margin-left: 20px" @click="downloadFile(scope.row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- "打包下载" (Pack & Download) button -->
      <el-button class="packDownload" type="primary" @click="packAndDownload">打包下载</el-button>&emsp;<span>(打包成一个压缩包)</span>
      <div class="showCurrentStatus" v-if="formData">
        <span>提交状态:</span>  {{ formData.archiveSubmitStatus }}&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; <span>提交时间:</span>  {{ formData.archiveSubmitTime }}<br><br>
        <span>审批状态:</span>  {{ formData.archiveApproveStatus }}&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; <span>审批时间:</span>  {{ formData.archiveApproveTime }}
      </div>


      <!-- 审批意见 -->
      <el-form>
        <el-form-item  class="inputApproval" label="审批意见:">
          <el-input v-model="archiveApproveSuggestion" type="textarea" rows="4" placeholder="请输入审批意见"></el-input>
        </el-form-item>
        <el-form-item>
          <template slot-scope="scope">
            <el-button type="primary" @click="approve">审批通过</el-button>
            <el-button type="primary" v-if="canCancel" @click="cancel">审批退回</el-button>
          </template>
        </el-form-item>
      </el-form>

      <!-- 返回按钮 -->
      <el-button class="back-button" @click="goBack" type="primary">返回</el-button>

    </el-main>
  </div>
</template>

<script>
//npm install jszip file-saver  引入jszip
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import request from "@/utils/request";
import {archiveApproved, archiveCancel } from "@/api/archiveApproval/archiveApproval";
import {selectAllArchiveManger} from "@/api/archive/archive";


export default {
  data() {
    return {
      //保存传递过来的数据
      formData: {
        projectCode: '',
        projectName: '',
        categoryName: '',
        budget: '',
        archiveSubmitStatus:'',
        archiveSubmitTime:'',
        archiveApproveStatus:'',
        archiveApproveTime:'',
        projectId:'',
      },

      projectTable: [
        //测试数据，上线前请将代码删除
        {
          id:'1',
          fileCategory: '采购通知书',
          fileName: 'xxx项目通知书.PDF',
          filePath:'',
          fileArchiveTime: '2023-07-26 12:34:56',
        },
        {
          id:'2',
          fileCategory: '采购通文档',
          fileName: 'xxx项目通知书.docx',
          filePath:'',
          fileArchiveTime: '2023-08-3 15:43:26',
        }
      ],
      theData: [], // 新添加的属性
      failureDialogVisible: false,
      loading: true,
      archiveApproveSuggestion: '',

    };
  },

  created() {
    // 接收路由传递的数据
    this.formData.projectCode = this.$route.params.projectCode;
    this.formData.projectName = this.$route.params.projectName;
    this.formData.categoryName = this.$route.params.categoryName;
    this.formData.budget = this.$route.params.budget;
    this.formData.archiveSubmitStatus = this.$route.params.archiveSubmitStatus;
    this.formData.archiveSubmitTime = this.$route.params.archiveSubmitTime;
    this.formData.archiveApproveStatus = this.$route.params.archiveApproveStatus;
    this.formData.archiveApproveTime = this.$route.params.archiveApproveTime;
    this.formData.projectId = this.$route.params.projectId;
    this.onload()
  },

  methods: {

    handleSizeChange(val) {
      this.pageSize = val
      this.onload()

    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.onload()
    },

    //初始化projectTable里的数据
    async selectAllProjectTable() {
      let data ={ projectId: this.formData.projectId }
      try {
        const response = await selectAllArchiveManger(data);
        if (response){
          this.loading = false
        }
        this.projectTable = response.data.data.archiveFileList;
        this.totalItems = this.projectTable.length;
      } catch (error) {
        console.error('Error fetching supplier data:', error);
      }
    },


    //下载
    async downloadFile(index, row){
      let data={
        'filePath':row.filePath
      }
      let res=await request(
          {
            url: "/archiveApprove/filedownload",
            method: "post",
            responseType: 'blob',
            data:data
          }
      )
      console.log(res.data)
      let blob = new Blob([res.data], {type: 'application/octet-stream'})
      // 创建一个临时的URL，用于下载文件
      let url = window.URL.createObjectURL(blob)
      // 创建一个a标签，指定下载链接和文件名
      let link = document.createElement('a')
      link.href = url
      link.download = row.filePath // 这里可以根据实际情况指定文件名和扩展名
      // 触发a标签的点击事件，开始下载文件
      link.click()
      // 释放URL资源
      window.URL.revokeObjectURL(url)
    },

    //打包下载
    async packAndDownload() {
      const zip = new JSZip();

      for (const file of this.projectTable) {
        try {
          const response = await this.downloadFile(file);
          const blob = new Blob([response.data], { type: 'application/octet-stream' });
          zip.file(file.fileName, blob);
        } catch (error) {
          console.error('Error downloading file:', error);
        }
      }

      const zipBlob = await zip.generateAsync({ type: 'blob' });
      FileSaver.saveAs(zipBlob, 'archive_Approval.zip');
    },
    // async packAndDownload() {
    //   const zip = new JSZip();
    //   const filePromises = [];
    //
    //   // 循环遍历归档文件列表，将文件内容添加到压缩包
    //   for (const file of this.projectTable) {
    //     //  file.filePath 表示文件的实际路径，可以根据实际情况进行修改
    //     const filePromise = fetch(file.filePath + file.fileName)
    //         .then(response => response.blob())
    //         .then(blob => {
    //           zip.file(file.fileName, blob);
    //         });
    //
    //     filePromises.push(filePromise);
    //   }
    //
    //   // 所有文件添加完成后，生成压缩包并提供下载链接
    //   Promise.all(filePromises)
    //       .then(() => {
    //         return zip.generateAsync({ type: 'blob' });
    //       })
    //       .then(zipBlob => {
    //         FileSaver.saveAs(zipBlob, 'archive_files.zip');
    //       });
    // },


    //审批通过
    async approve() {
      // 发出事件以更新index中的审批状态
      this.$confirm('确认通过吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {projectId:this.formData.projectId,archiveApproveSuggestion:this.archiveApproveSuggestion}
        let res = await archiveApproved(data)
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '通过成功!'
          });
          this.formData.archiveApproveStatus = '审批通过';
          // 审批后重置审批意见输入字段
          this.archiveApproveSuggestion = '';

        } else {
          this.$message.error(res.data.msg)
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消通过'
        });
      });
    },

    canCancel() {
      // 检查审批状态是否已为“审批通过“或者如果”审批通过”按钮
      return this.formData && this.formData.archiveApproveStatus === '审批通过';
    },


    //审批退回
    async cancel() {
      // 发出事件以更新index中的审批状态
      this.$confirm('确认取消审批吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {projectId:this.formData.projectId,archiveApproveSuggestion:this.archiveApproveSuggestion}
        let res = await archiveCancel(data)
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: '取消成功!'
          });
          this.formData.archiveApproveStatus = '审批退回';
          // 审批后重置审批意见输入字段
          this.archiveApproveSuggestion = '';

        } else {
          this.$message.error(res.data.msg)
        }

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已确认通过'
        });
      });
    },


    //返回archive
    goBack() {
      this.$router.push('archiveApproval');
    },

  },

};
</script>

<style>

.showCurrentStatus{
  margin-top: 30px;
}
.packDownload{
  margin-top: 30px;
}
.centered-buttons {
  text-align: center;
  margin-top: 20px;
}
.submit-button {
  margin-right: 20px;
}
.back-button{
  margin-top: 10px
}
</style>

